package com.kede.api.stand.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.kede.api.stand.dto.BuildPackageDTO;
import com.kede.api.stand.service.IPackageManageServer;
import com.kede.domain.PackageDomain;
import com.kede.domain.ZhiOrderGoodsListDomain;
import com.kede.domain.ZhiUserCertifiedDomain;
import com.kede.ienum.order.CertiTypeEnum;
import com.kede.ienum.store.CertiStatueEnum;
import com.kede.pojo.*;
import com.kede.service.PackageService;
import com.kede.service.ZhiOrderGoodsListService;
import com.kede.service.ZhiUserCertifiedService;
import com.kede.utils.CollectionUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Pr.li
 * @Date: create in 2023/9/16 11:14
 */
@Service
public class PackageManageServerImpl implements IPackageManageServer {

    @Resource
    private PackageService packageService;

    @Resource
    private ZhiUserCertifiedService zhiUserCertifiedService;

    @Resource
    private ZhiOrderGoodsListService zhiOrderGoodsListService;

    @Override
    public ResHttp buildPackage(BuildPackageDTO buildPackageDTO) {
        StringBuilder goodIds = new StringBuilder();
        List<ZhiOrderGoodsListDomain> goodList = buildPackageDTO.getGoodList();
        BigDecimal weight = new BigDecimal("0");
        for (int i = 0,len = goodList.size(); i < len; i++) {
            ZhiOrderGoodsListDomain goodsListDomain = goodList.get(i);
            goodIds.append(goodsListDomain.getId());
            if (i < len -1 ){
                goodIds.append(",");
            }
            if(goodsListDomain.getOrderSn().indexOf(ZhiTypeEnum.DEBIWEIGHT.getOrderKey()) != -1){
                //是称重得包裹
                weight = weight.add(goodsListDomain.getWeight());
            }
            goodsListDomain.setGoodPackageStatus(GoodPackageStatus.Packaged.getStatus());
            zhiOrderGoodsListService.updateById(goodsListDomain);
        }
        PackageDomain packageDomain = new PackageDomain();
        packageDomain.setCount(buildPackageDTO.getGoodList().size());
        packageDomain.setWeight(weight);
        packageDomain.setCateName(buildPackageDTO.getCateName());
        packageDomain.setGoodIds(goodIds.toString());

        LocalDateTime now = LocalDateTime.now();
        ZhiUserCertifiedDomain certifiedDomain = zhiUserCertifiedService.getOneByUserId(buildPackageDTO.getUserId());
        switch (buildPackageDTO.getCertitype()){
            case STORE:
                packageDomain.setStoreCreateTime(now);
                packageDomain.setStoreId(certifiedDomain.getId());
                packageDomain.setStoreName(certifiedDomain.getStoreName());
                packageDomain.setStatus(PackageStatusEnum.StoreNormal.getStatus());
                break;
            case QUDAI:
                packageDomain.setQuCreateTime(now);
                packageDomain.setQuId(certifiedDomain.getId());
                packageDomain.setQuName(certifiedDomain.getStoreName());
                packageDomain.setStatus(PackageStatusEnum.QuNormal.getStatus());
                break;
            case SHIDAI:
                packageDomain.setShiCreateTime(now);
                packageDomain.setShiId(certifiedDomain.getId());
                packageDomain.setShiName(certifiedDomain.getStoreName());
                packageDomain.setStatus(PackageStatusEnum.ShiNormal.getStatus());
                break;
        }

        boolean save = packageService.save(packageDomain);
        if (save){
            return ResHttp.okData(packageDomain);
        }
        return ResHttp.fail();
    }

    @Override
    public ResHttp getMyPackage(PagePO pagePO, Integer cerId, CertiTypeEnum type, PackageStatusEnum status) {
        List<OrderItem> orders = pagePO.orders();
        if (CollectionUtil.Blank(orders)){
            orders.add(OrderItem.desc("id"));
        }
        LambdaQueryWrapper<PackageDomain> queryWrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotNull(status)){
            queryWrapper.eq(PackageDomain::getStatus,status.getStatus());
        }
        queryWrapper.isNotNull(PackageDomain::getTransportNo);
        switch (type){
            case STORE:
                queryWrapper.eq(PackageDomain::getStoreId,cerId);
                break;
            case QUDAI:
                queryWrapper.eq(PackageDomain::getQuId,cerId);
                break;
            case SHIDAI:
                queryWrapper.eq(PackageDomain::getShiId,cerId);
                break;
        }
        PagePO page = packageService.page(pagePO, queryWrapper);
        return ResHttp.okData(page);
    }

    @Override
    public ResHttp getPackageDetail(Integer id, CertiTypeEnum type) {
        PackageDomain packageDomain = packageService.getById(id);
        BigDecimal totalMoney = new BigDecimal("0");
        String[] goodIds = packageDomain.getGoodIds().split(",");
        for (String goodId : goodIds) {
            ZhiOrderGoodsListDomain good = zhiOrderGoodsListService.getById(goodId);
            totalMoney = totalMoney.add(getMoney(good,type));
            packageDomain.getGoodsList().add(good);
        }
        packageDomain.setTotalMoney(totalMoney);
        return ResHttp.okData(packageDomain);
    }

    /**
     * 现在的逻辑是只有 门店可以对包裹进行操作，所以下面用的  getDefaultStoreMoney
     * @param packageId
     * @param goodId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResHttp removeGood(Integer packageId,Integer goodId) {
        PackageDomain pge = packageService.getById(packageId);
        Integer count = pge.getCount();
        ZhiOrderGoodsListDomain good = zhiOrderGoodsListService.getById(goodId);
        if( count <= 1){
            //最后一件物品就删除该包裹了
            packageService.removeById(packageId);
        }else{
            String a = pge.getGoodIds();
            a =a.replaceFirst("(,"+goodId+",)", ",");
            a = a.replaceFirst("(^"+goodId+",)|(,"+goodId+"$)","");
            pge.setGoodIds(a);
            pge.setWeight(pge.getWeight().subtract(good.getWeight()));
            pge.setCount(--count);
            packageService.updateById(pge);
        }
        good.setGoodPackageStatus(GoodPackageStatus.UnPackage.getStatus());
        zhiOrderGoodsListService.updateById(good);
        return ResHttp.ok();
    }

    @Override
    public ResHttp getParentInfoByAddress(CertiTypeEnum type, String addres) {
        String[] split = addres.split(",");
        LambdaQueryWrapper<ZhiUserCertifiedDomain> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZhiUserCertifiedDomain::getSheng,split[0]);
        queryWrapper.eq(ZhiUserCertifiedDomain::getShi,split[1]);
        queryWrapper.eq(ZhiUserCertifiedDomain::getQu,split[2]);
        queryWrapper.eq(ZhiUserCertifiedDomain::getType,type.getCode());
        queryWrapper.eq(ZhiUserCertifiedDomain::getStatus, CertiStatueEnum.APPROVED.getEnumIndex());
        ZhiUserCertifiedDomain one = zhiUserCertifiedService.getOne(queryWrapper);
        return ResHttp.okData(one);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResHttp removePkg(Integer packageId) {

        PackageDomain pkg = packageService.getById(packageId);
        String[] goodIds = pkg.getGoodIds().split(",");
        List<ZhiOrderGoodsListDomain> list = new ArrayList<>();
        for (String sgoodId : goodIds) {
            ZhiOrderGoodsListDomain good = zhiOrderGoodsListService.getById(sgoodId);
            good.setGoodPackageStatus(GoodPackageStatus.UnPackage.getStatus());
            list.add(good);
        }
        zhiOrderGoodsListService.updateBatchById(list);
        packageService.removeById(packageId);
        return ResHttp.ok();
    }

    @Override
    public ResHttp normalPkg(Integer packageId,CertiTypeEnum typeEnum) {
        PackageDomain pkg = packageService.getById(packageId);
        //这里的拒绝原因是处理成空
        pkg.setReason("");
        switch (typeEnum){
            case STORE:
                pkg.setStatus(PackageStatusEnum.StoreNormal.getStatus());
                pkg.setStoreCreateTime(LocalDateTime.now());
                break;
            case QUDAI:
                pkg.setStatus(PackageStatusEnum.QuNormal.getStatus());
                pkg.setQuCreateTime(LocalDateTime.now());
                break;
        }
        packageService.updateById(pkg);
        return ResHttp.ok();
    }

    private BigDecimal getMoney(ZhiOrderGoodsListDomain good,CertiTypeEnum type){
        switch (type){
            case STORE:
                return good.getDefaultStoreMoney();
            case QUDAI:
                return good.getDefaultQuMoney();
            case SHIDAI:
                return good.getDefaultShiMoney();
        }
        return null;
    }


}
